package com.lcn.netty.manager;

import com.lcn.netty.handler.ChatHandler;
import com.lcn.pojo.netty.ChatMsg;
import com.lcn.pojo.netty.DataContent;
import com.lcn.utils.JsonUtils;
import com.lcn.utils.LocalDateUtils;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会话管理
 * 用户id和channel的关联处理
 */
public class UserChannelSession {

    // 多端同时接收消息，允许同一个账号在多个设备同时在线
    private static Map<String, List<Channel>> multiSession = new HashMap<>();

    // channelId -> userId
    private static Map<String, String> userChannelIdMap = new HashMap<>();

    public static void putUserChannelIdMap(String channelId, String userId) {
        userChannelIdMap.put(channelId, userId);
    }

    public static String getUserIdByChannelId(String channelId) {
        return userChannelIdMap.get(channelId);
    }

    public static void putMultiSession(String userId, Channel channel) {
        List<Channel> channels = multiSession.get(userId);
        if (channels == null || channels.size() == 0) {
            channels = new ArrayList<>();
        }
        channels.add(channel);
        multiSession.put(userId, channels);
    }

    public static List<Channel> getMultiSession(String userId) {
        return multiSession.get(userId);
    }

    /**
     * 获取除了当前频道之外的所有频道
     */
    public static List<Channel> getMyOtherChannel(String userId, String channelId) {
        List<Channel> channels = multiSession.get(userId);
        if (channels == null || channels.size() == 0) {
            return null;
        }
        List<Channel> otherChannels = channels.stream()
                .filter(channel ->
                        channel != null &&
                        !channel.id().asLongText().equals(channelId))
                .collect(Collectors.toList());
        return otherChannels;
    }

    /** 移除用户的某个会话 */
    public static void removeMultiSession(String userId, String channelId) {
        List<Channel> channels = multiSession.get(userId);
        if (channels == null || channels.size() == 0) {
            return;
        }
        for (int i = 0; i < channels.size(); i++) {
            Channel channel = channels.get(i);
            if (channelId.equals(channel.id().asLongText())) {
                channels.remove(i);
            }
        }
        multiSession.put(userId, channels);
    }

    /** 打印多端连接信息 */
    public static void outputMulti() {
        multiSession.forEach((userId, channels) -> {
            channels.forEach(channel -> {
                System.out.println("userId = " + userId + " , channelId = " + channel.id().asLongText());
            });
            System.out.println("=======================");
        });
    }

    /**
     * netty发送聊天消息
     */
    public static void sendToTarget(List<Channel> channels, DataContent dataContent) {
        ChannelGroup clients = ChatHandler.clients;
        if (channels == null || channels.size() == 0) {
            return;
        }
        for (Channel channel : channels) {
            Channel findChannel = clients.find(channel.id());
            if (findChannel != null) {
                // 发送消息
                channel.writeAndFlush(new TextWebSocketFrame(JsonUtils.objectToJson(dataContent)));
            }
        }
    }

}
